<template>
  <div style="position:relative">饼图显示
    <div class="bottom" id="echart" ref="mychart"></div>
    <div class="box_container">
      <percent-box :percent="currentPercent" :labelText="labelText"></percent-box>
    </div>
  </div>
</template>

<script>
import echarts from 'echarts'
import percentBox from '@/components/percent_box'
// import _ from 'lodash'
export default {
  components: {
    percentBox
  },
  name: 'pieTest',
  data() {
    return {
      myChart: {},
      option: {
        // 提示框
        tooltip: {
          trigger: 'none',
          formatter: '{b}: {c} ({d}%)' // 饼图、雷达图、仪表盘、漏斗图: a（系列名称），b（数据项名称），c（数值）, d（饼图：百分比 | 雷达图：指标名称）
        },
        color: [
          '#7EC0EE',
          '#FF9F7F',
          '#FFD700',
          '#C9C9C9',
          '#E066FF',
          '#C0FF3E'
        ], // 设置默认的调色盘，在未指定颜色时，顺序选择
        legend: {
          orient: 'vertical',
          selectedMode: false,
          x: 'left',
          data: ['已入住', '装修中', '空置', '出租'],
          textStyle: {
            color: '#fff' // 图例文字颜色
          }
        },
        series: [
          {
            name: '房屋统计状态',
            type: 'pie',
            silent: true,
            radius: ['50%', '70%'],
            // avoidLabelOverlap: false,
            // animation: false,
            label: {
              normal: {
                show: false,
                position: 'center'
              }
              // emphasis: {
              //   show: true,
              //   // formatter: '{d}%\n{b}',
              //   formatter: (v) => {
              //     return '2222'
              //   },
              //   textStyle: {
              //     fontSize: '30',
              //     fontWeight: 'bold',
              //     color: '#fff'
              //   }
              // }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: [
              { value: 10, name: '已入住' },
              { value: 50, name: '装修中' },
              { value: 1000, name: '空置' },
              { value: 400, name: '出租' }
            ]
          }
        ],
        animationDurationUpdate: function(idx) {
          // 越往后的数据延迟越大
          return idx * 1000
        }
      },
      refreshBarSetInterval: {},
      nowIndex: -1,
      currentPercent: 0,
      labelText: ''
    }
  },
  created() {
    this.labelText = this.option.series[0].data.name
  },
  mounted() {
    this.$nextTick(() => {
      this.initEchart()
      this.setAnimation()
    })

    // var hiddenProperty = 'hidden' in document ? 'hidden' : 'webkitHidden' in document ? 'webkitHidden' : 'mozHidden' in document ? 'mozHidden' : null
    // var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange')

    // var onVisibilityChange = () => {
    //   if (!document[hiddenProperty]) {
    //     console.log('页面非激活')
    //     clearInterval(this.refreshBarSetInterval)
    //     this.refreshBarSetInterval = null
    //   } else {
    //     console.log('页面激活')
    //     clearInterval(this.refreshBarSetInterval)
    //     this.refreshBarSetInterval = null
    //     this.setAnimation()
    //   }
    // }
    // document.addEventListener(visibilityChangeEvent, onVisibilityChange)

    // window.onfocus = () => {
    //   console.log('聚焦')
    //   this.setAnimation()
    // }

    // window.onblur = () => {
    //   console.log('失焦')
    //   clearInterval(this.refreshBarSetInterval)
    //   this.refreshBarSetInterval = null
    // }

    document.onvisibilitychange = () => { // 定时器一坑踩完
      if (document.visibilityState !== 'visible') {
        clearInterval(this.refreshBarSetInterval)
        this.refreshBarSetInterval = null
      } else {
        this.setAnimation()
      }
    }
  },
  methods: {
    // 创建实例并生成表格
    initEchart() {
      this.myChart = echarts.init(this.$refs.mychart) // 创建实例
      this.myChart.setOption(this.option) // 生成图表
    },

    setAnimation() {
      const cData = this.option.series[0].data
      const dataLen = cData.length
      const total = cData.reduce((pre, total) => {
        return {
          ...total,
          value: pre.value + total.value
        }
      }).value
      this.refreshBarSetInterval = setInterval(() => {
        this.myChart.dispatchAction({
          type: 'downplay',
          seriesIndex: 0,
          dataIndex: this.nowIndex
        })
        this.nowIndex = (this.nowIndex + 1) % dataLen
        this.currentPercent = Math.ceil(
          (cData[this.nowIndex].value / total) * 100
        )
        this.myChart.dispatchAction({
          type: 'highlight',
          seriesIndex: 0,
          dataIndex: this.nowIndex
        })
        this.labelText = cData[this.nowIndex].name
      }, 2000)
    }
  },
  destroyed() {
    clearInterval(this.refreshBarSetInterval)
  }
}
</script>

<style lang='scss' scoped>
.box_container {
  position: absolute;
  top: 200px;
  left: 300px;
}
.bottom {
  width: 600px;
  height: 400px;
  background-color: #051930;
}
</style>
